package com.chenwc.netty.tcp.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author chenwc
 * @date 2023/5/21 17:04
 */
public class KeepAliveTask extends Thread {

    private static final Logger log = LoggerFactory.getLogger(KeepAliveTask.class);
    //是否在运行
    public volatile boolean isRunning = true;
    //过期时间，单位s
    private final long ttlSeconds;
    private final KeepAliveAction action;
    
    private final String name;

    /**
     * 保持锁不过期的任务
     * @param action KeepAliveAction
     * @param ttlSeconds 过期时间，单位s
     */
    public KeepAliveTask(KeepAliveAction action, long ttlSeconds, String name) {
        this.ttlSeconds = ttlSeconds;
        this.action = action;
        this.name = name;
        this.setDaemon(true);
    }

    @Override
    public void run() {
        // 每隔三分之一过期时间，续租一次
        final long sleep = this.ttlSeconds * 1000 / 3;
        log.info("开启定时任务：{}", name);
        while (isRunning) {
            try {
                // 1、续租，刷新值
                action.run();
                log.debug("续租成功!");
                TimeUnit.MILLISECONDS.sleep(sleep);
            } catch (InterruptedException | DtLockException e) {
                close();
            }
        }
    }

    public void close() {
        log.info("停止定时任务：{}", name);
        isRunning = false;
        this.interrupt();
        System.exit(0);
    }
}
